// pages/scan/scan.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    BarCode:'',
    useBtn:false,
    tag:0,
    score:'',
    resList:[],
    imgList: [],
    upimgList:[],
    index: null,
    textareaAValue:'',
    picker: ['全新','良好', '中等', '旧书']
  },
  // 书籍信息
  getbookmsg:function(e){
    let that=this;
    let err1 = "isbn 错误! 详情见 https://jike.xyz/jiekou/isbn.html"
    let err2 = "请求过快！ sleep:2s; 详情见 https://jike.xyz/jiekou/isbn.html"
    wx.request({
      url: 'https://api.jike.xyz/situ/book/isbn/'+e+'?apikey=13015.32a334a3861a47b3e2f586a240fb4403.1f5bc77f9bb0d34e517cee5aa5cdb103',
      method:'GET',
      success (res) {
        if(res.data.msg == err1){
          wx.showModal({
            title:"提示",
            content:"ISBN码有误,再检查一下吧",
            confirmText:"好的",
            showCancel:false,
            success:(res)=>{
              wx.navigateBack({
                delta: 1,
              })
            }
          })
        }else if(res.data.msg == err2){
          wx.showModal({
            title:"提示",
            content:"操作太频繁,休息一下再来吧",
            confirmText:"好的",
            showCancel:false,
            success:(res)=>{
              wx.navigateBack({
                delta: 1,
              })
            }
          })
        }else{
          wx.showToast({
            title: '扫描成功',
          })
        }
        that.setData({
          resList:res.data.data
        })
        // console.log(that.data.resList)
        }
    })
  },
  PickerChange(e) {
    // console.log(e);
    this.setData({
      index: e.detail.value
    })
  },
  // 商品描述
  textareaAInput(e) {
    this.setData({
      textareaAValue: e.detail.value
    })
  },
  // 获取积分
  getscore(e){
    this.setData({
      score:e.detail.value
    })
    // console.log(this.data.score)
  },
  // 选择图片
  ChooseImage() {
    wx.chooseImage({
      count: 4, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }

      }
    });
  },
  // 删除图片
  DelImg(e) {
    wx.showModal({
      title: '提示',
      content: '确定要删除这张照片吗？',
      cancelText: '不了',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  //预览图片
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  //提交表单+图片
  bindSubmit(e){
    console.log(e)
    wx.showModal({
      title:"提示",
      content:"确认发布这本书籍吗?",
      success:(res)=>{
        if(res.confirm){
        // console.log(this.data.imgList)
        for(; this.data.tag < this.data.imgList.length;this.data.tag++){
          wx.uploadFile({
            filePath: this.data.imgList[this.data.tag],
            name: 'files',
            url: 'http://124.222.95.170:21311/common/upload',
            header: {
              'Cookie': wx.getStorageSync('sessionid')
            },
            success:(res)=>{     
              console.log(JSON.parse(res.data).data[0])   
              this.setData({
                upimgList: this.data.upimgList.concat(JSON.parse(res.data).data)
          
              })
              console.log(this.data.upimgList.length)

              //发送数据
              //当上传的图片数目等于用户已选择的图片数目时，说明上传完成
              //接着就可以发送提交书籍的请求了
              if(this.data.upimgList.length == this.data.imgList.length) {
                wx.request({
                  url: 'http://124.222.95.170:21311/goods',
                  method:'POST',
                  header: {
                    'Cookie': wx.getStorageSync('sessionid')
                  },
                  header:{
                    "Content-Type": "application/json"
                  },
                  data:{
                        "bookInfo":{
                          "isbn":this.data.resList.id,
                          "author":this.data.resList.author,
                          "image":this.data.resList.photoUrl,
                          "name":this.data.resList.name,
                          "press":this.data.resList.publishing
                        },
                        "goods":{
                          "description":e.detail.value.bkTxt,
                          "integral":e.detail.value.bkScore,
                          "level":e.detail.value.bkNew,
                          // "userId":2
                        },
                        "picturesUrl":this.data.upimgList
        
                  },
                  success: (res) =>{
                    // console.log(res)
                    console.log('发送成功',res)
                    if(res.data.msg == "该书已发布"){
                      this.data.useBtn = !this.data.useBtn,
                      wx.showModal({
                        title:"提示",
                        content:"已经发布过这本书啦ヾ(•ω•`)o"
                      })
                    }else if(res.data.msg == "请上传至少一张图片"){
                      wx.showModal({
                        title:"提示",
                        content:"请上传至少一张图片ヾ(•ω•`)o"
                      })
                    }else if(res.data.msg == "请设置积分"){
                      wx.showModal({
                        title:"提示",
                        content:"请设置积分ヾ(•ω•`)o"
                      })
                    }else if(res.data.msg == "积分范围有误"){
                      wx.showModal({
                        title:"提示",
                        content:"积分范围有误ヾ(•ω•`)o"
                      })
                    }else if(res.data.msg == "请选择书本品相"){
                      wx.showModal({
                        title:"提示",
                        content:"请选择书本品相ヾ(•ω•`)o"
                      })
                    }else if(res.data.msg == "描述不可为空"){
                      wx.showModal({
                        title:"提示",
                        content:"描述不可为空ヾ(•ω•`)o"
                      })
                    }else{
                      wx.navigateTo({
                        url: '/pages/upresult/upresult',
                      })    
                    }
                  },
                  fail:(e)=>{
                    console.log('发送失败')
                  }
                })
              }
            }
          })
        }
        }
      }
    })
  },

   /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
//  console.log("options>>", options.barcode);
    this.setData({
      BarCode : options.barcode
    })
  this.getbookmsg(options.barcode);
   },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})